package fr.p10.miage.m1.sr.tcpclient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;

/**
 * Simple client TCP en boucle d'interaction avec un serveur.
 * Envoie au serveur un message lu au clavier, puis affiche 
 * la reponse du serveur.
 * @author lom
 */
public class ClientTCP {

    /**
     * Port de connexion.
     */
    private static final int PORT = 6792;
    /**
     * "Server unreachable" message to display to user.
     */
    private static final String UNREACHABLE = "CLIENT: Server unreachable. Stopping.";
    /**
     * "Waiting for server response" message to display to user.
     */
    private static final String WAITING = "CLIENT: waiting for server response...";
    /**
     * Good bye message.
     */
    private static final String BYE = "BYE";
    /**
     * Client stops.
     */
    private static final String END = "CLIENT: BYE.";
    /**
     * New line.
     */
    private static final String NL = "\n";

    public static void main(String argv[]) throws Exception {
        String sentence;
        String answer;
        StringBuilder serverResponse = new StringBuilder();
        InetAddress IPAddress = InetAddress.getLocalHost();
        Socket clientSocket =
                new Socket(IPAddress, PORT);
        BufferedReader inFromUser =
                new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream outToServer =
                new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer =
                new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        while (true) {
            outToServer.writeBytes(sentence + NL);
            if (BYE.equalsIgnoreCase(sentence.trim())){
                break;
            }
            System.err.println(WAITING);
            try{
                while(!"".equals(answer = inFromServer.readLine()))
                    serverResponse.append(answer).append(NL);
            } catch (SocketException se){
                System.err.println(UNREACHABLE);
                break;
            }
            System.out.println("FROM SERVER: " + NL + serverResponse.toString());
            serverResponse.delete(0, serverResponse.length());
            sentence = inFromUser.readLine();
        }
        System.err.println(END);
        clientSocket.close();
    }
}
